package ca.uvic.group2.server;

import java.sql.*; 
import ca.uvic.group2.server.*;
import ca.uvic.group2.api.exceptions.*;

public class JDBCConnection 
{ 
	// the connection pool for that database instance 
	private JDBCConnectionImpl.JDBCPool connectionPool; 
	//the connection
	private JDBCConnectionImpl impl;
	//statement and resultset
	private Statement stmt;
	private ResultSet rs;
	//is there a resultset in use?
	//private Boolean inUse;
	private boolean inUse;
        
	//get connection to database pool
	public JDBCConnection () 
	{ 
		System.out.println("JDBCConnection: start"); 
		connectionPool = JDBCConnectionImpl.JDBCPool.getInstance(); 
		inUse = false;
		System.out.println("JDBCConnection: end");
	} 
	
	//send a request to the database
	void sendRequest (String sqlString) throws SQLException, ClassNotFoundException //, PoolException
	{
		if(inUse)
			closeRequest();
		try
		{
			impl = connectionPool.acquireImpl();
			if(impl == null)
			{
				System.out.println("JDBCConnectionImpl returned is null");
			}
				
			
			stmt = impl.getConnection().createStatement();
			rs = stmt.executeQuery(sqlString);
			inUse = true;
		}
		catch(PoolException pe)
		{
			System.out.println("blarg!!!");
			
		}
	}
	
	int sendUpdate (String sqlString) throws SQLException, ClassNotFoundException//, PoolException 
	{
		int rows = 0;
		
	    if (inUse)
	      closeRequest();
		try
		{
			impl = connectionPool.acquireImpl();
		    stmt = impl.getConnection().createStatement();
		    rows = stmt.executeUpdate(sqlString);
		}
	    catch(PoolException pe)
		{
			System.out.println("Pool Exception: " + pe);			
		}
	    inUse = true;
	    return rows;
	}
	
	
	//return the resultSet of the request
	ResultSet getRs()
	{
		return rs;
	}
	
	//closeRequest and return resources
	void closeRequest() throws SQLException
	{
		System.out.println("JDBCConnection: closing request");		
		if(rs != null)
			rs.close();
		if(stmt != null)
			stmt.close();
		
		connectionPool.releaseImpl(impl);
		inUse = false;
	}
	
	//free resources when object is destroyed
	protected void finalize() throws SQLException
	{
		if(inUse)
			closeRequest();
	}
	
	// send a request to the database and return the result 
	/* ResultSet sendRequest (String sqlString /*, ResultSet rs/) throws SQLException, ClassNotFoundException 
	{ 
		ResultSet rs = null;
		System.out.println("sendRequest: start");
		JDBCConnectionImpl impl = connectionPool.acquireImpl(dbName); 
		System.out.println("sendRequest: sqlString" + sqlString);
		rs = impl.sendRequest(sqlString);//, rs); 
		connectionPool.releaseImpl(impl); 
		System.out.println("sendRequest: end");
		return rs; 
	} */
}